using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Text;
using System.Windows.Forms;

using Trinity.Common;
using Trinity.DAL;
using Trinity.Workflow;
using MpowerSystems.MpxConnector;
using MpowerSystems.MpxConnector.Entities;
using LumenWorks.Framework.IO.Csv;

namespace Prydocon.Mpower.MpxAddressUpdateUtility
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class frmMain : System.Windows.Forms.Form
	{
        private const string _reportName = "Mpx Address Update Utility Export";
        private MpxConnection _mpxConnection = null;

        private System.Windows.Forms.TabControl tabControlMain;
        private System.Windows.Forms.TabPage tabOutputAddresses;
        private Panel panel1;
        private Label label2;
        private Label label1;
        private ComboBox cmbSegGroup;
        private ComboBox cmbSegJob;
        private RadioButton rbAllAccounts;
        private RadioButton rbSegmentationInput;
        private Label label4;
        private Label label3;
        private Panel panel2;
        private Label label7;
        private SaveFileDialog saveFileDialog;
        private Button btnSaveDialog;
        private TextBox txtOutputFile;
        private Button btnOutputAddresses;
        private TabPage tabImportAddresses;
        private Button btnImportAddresses;
        private Panel panel3;
        private Button btnOpenDialog;
        private TextBox txtInputFile;
        private Label label5;
        private Label label6;
        private Panel panel4;
        private Label label8;
        private Label label9;
        private ComboBox cmbNoteType;
        private TextBox txtNoteValue;
        private CheckBox chkAddNote;
        private CheckBox chkProperCase;
        private CheckBox chkAddCode;
        private Label label10;
        private Label label11;
        private ComboBox cmbCodeType;
        private ComboBox cmbCodeValue;
        private StatusStrip statusStrip1;
        private ToolStripStatusLabel toolStripStatusLabel;
        private MenuStrip menuStrip;
        private ToolStripMenuItem fileToolStripMenuItem;
        private ToolStripMenuItem outputToolStripMenuItem;
        private ToolStripMenuItem inputToolStripMenuItem;
        private ToolStripMenuItem helpToolStripMenuItem;
        private ToolStripMenuItem aboutToolStripMenuItem;
        private OpenFileDialog openFileDialog;
        private ToolStripMenuItem connectToMPXToolStripMenuItem;
        private ToolStripSeparator toolStripMenuItem1;
        private ToolStripMenuItem disconnectFromMPXToolStripMenuItem;
		/// <summary>
		/// Required designer variable.
		/// </summary>
		private System.ComponentModel.Container components = null;

		public frmMain()
		{
			//
			// Required for Windows Form Designer support
			//
			InitializeComponent();

			//
			// TODO: Add any constructor code after InitializeComponent call
			//
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			if( disposing )
			{
				if (components != null) 
				{
					components.Dispose();
				}
			}
			base.Dispose( disposing );
		}

		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frmMain));
            this.tabControlMain = new System.Windows.Forms.TabControl();
            this.tabOutputAddresses = new System.Windows.Forms.TabPage();
            this.btnOutputAddresses = new System.Windows.Forms.Button();
            this.panel2 = new System.Windows.Forms.Panel();
            this.btnSaveDialog = new System.Windows.Forms.Button();
            this.txtOutputFile = new System.Windows.Forms.TextBox();
            this.label7 = new System.Windows.Forms.Label();
            this.panel1 = new System.Windows.Forms.Panel();
            this.label2 = new System.Windows.Forms.Label();
            this.label1 = new System.Windows.Forms.Label();
            this.cmbSegGroup = new System.Windows.Forms.ComboBox();
            this.cmbSegJob = new System.Windows.Forms.ComboBox();
            this.rbAllAccounts = new System.Windows.Forms.RadioButton();
            this.rbSegmentationInput = new System.Windows.Forms.RadioButton();
            this.label4 = new System.Windows.Forms.Label();
            this.label3 = new System.Windows.Forms.Label();
            this.tabImportAddresses = new System.Windows.Forms.TabPage();
            this.panel4 = new System.Windows.Forms.Panel();
            this.cmbCodeValue = new System.Windows.Forms.ComboBox();
            this.chkProperCase = new System.Windows.Forms.CheckBox();
            this.chkAddCode = new System.Windows.Forms.CheckBox();
            this.label10 = new System.Windows.Forms.Label();
            this.label11 = new System.Windows.Forms.Label();
            this.cmbCodeType = new System.Windows.Forms.ComboBox();
            this.txtNoteValue = new System.Windows.Forms.TextBox();
            this.chkAddNote = new System.Windows.Forms.CheckBox();
            this.label8 = new System.Windows.Forms.Label();
            this.label9 = new System.Windows.Forms.Label();
            this.cmbNoteType = new System.Windows.Forms.ComboBox();
            this.btnImportAddresses = new System.Windows.Forms.Button();
            this.panel3 = new System.Windows.Forms.Panel();
            this.btnOpenDialog = new System.Windows.Forms.Button();
            this.txtInputFile = new System.Windows.Forms.TextBox();
            this.label5 = new System.Windows.Forms.Label();
            this.label6 = new System.Windows.Forms.Label();
            this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
            this.statusStrip1 = new System.Windows.Forms.StatusStrip();
            this.toolStripStatusLabel = new System.Windows.Forms.ToolStripStatusLabel();
            this.menuStrip = new System.Windows.Forms.MenuStrip();
            this.fileToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.connectToMPXToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.toolStripMenuItem1 = new System.Windows.Forms.ToolStripSeparator();
            this.outputToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.inputToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.helpToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.aboutToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.openFileDialog = new System.Windows.Forms.OpenFileDialog();
            this.disconnectFromMPXToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
            this.tabControlMain.SuspendLayout();
            this.tabOutputAddresses.SuspendLayout();
            this.panel2.SuspendLayout();
            this.panel1.SuspendLayout();
            this.tabImportAddresses.SuspendLayout();
            this.panel4.SuspendLayout();
            this.panel3.SuspendLayout();
            this.statusStrip1.SuspendLayout();
            this.menuStrip.SuspendLayout();
            this.SuspendLayout();
            // 
            // tabControlMain
            // 
            this.tabControlMain.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.tabControlMain.Controls.Add(this.tabOutputAddresses);
            this.tabControlMain.Controls.Add(this.tabImportAddresses);
            this.tabControlMain.Location = new System.Drawing.Point(8, 29);
            this.tabControlMain.Name = "tabControlMain";
            this.tabControlMain.SelectedIndex = 0;
            this.tabControlMain.Size = new System.Drawing.Size(408, 320);
            this.tabControlMain.TabIndex = 0;
            // 
            // tabOutputAddresses
            // 
            this.tabOutputAddresses.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.tabOutputAddresses.Controls.Add(this.btnOutputAddresses);
            this.tabOutputAddresses.Controls.Add(this.panel2);
            this.tabOutputAddresses.Controls.Add(this.panel1);
            this.tabOutputAddresses.Controls.Add(this.label3);
            this.tabOutputAddresses.Location = new System.Drawing.Point(4, 22);
            this.tabOutputAddresses.Name = "tabOutputAddresses";
            this.tabOutputAddresses.Size = new System.Drawing.Size(400, 294);
            this.tabOutputAddresses.TabIndex = 0;
            this.tabOutputAddresses.Text = "Output Addresses";
            // 
            // btnOutputAddresses
            // 
            this.btnOutputAddresses.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
            this.btnOutputAddresses.Location = new System.Drawing.Point(129, 262);
            this.btnOutputAddresses.Name = "btnOutputAddresses";
            this.btnOutputAddresses.Size = new System.Drawing.Size(128, 23);
            this.btnOutputAddresses.TabIndex = 10;
            this.btnOutputAddresses.Text = "Output Addresses";
            this.btnOutputAddresses.UseVisualStyleBackColor = true;
            this.btnOutputAddresses.Click += new System.EventHandler(this.btnOutputAddresses_Click);
            // 
            // panel2
            // 
            this.panel2.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.panel2.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.panel2.Controls.Add(this.btnSaveDialog);
            this.panel2.Controls.Add(this.txtOutputFile);
            this.panel2.Controls.Add(this.label7);
            this.panel2.Location = new System.Drawing.Point(8, 201);
            this.panel2.Name = "panel2";
            this.panel2.Size = new System.Drawing.Size(376, 54);
            this.panel2.TabIndex = 9;
            // 
            // btnSaveDialog
            // 
            this.btnSaveDialog.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.btnSaveDialog.Location = new System.Drawing.Point(339, 24);
            this.btnSaveDialog.Name = "btnSaveDialog";
            this.btnSaveDialog.Size = new System.Drawing.Size(25, 20);
            this.btnSaveDialog.TabIndex = 14;
            this.btnSaveDialog.Text = "...";
            this.btnSaveDialog.UseVisualStyleBackColor = true;
            this.btnSaveDialog.Click += new System.EventHandler(this.btnSaveDialog_Click);
            // 
            // txtOutputFile
            // 
            this.txtOutputFile.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.txtOutputFile.Location = new System.Drawing.Point(8, 24);
            this.txtOutputFile.Name = "txtOutputFile";
            this.txtOutputFile.Size = new System.Drawing.Size(328, 20);
            this.txtOutputFile.TabIndex = 13;
            // 
            // label7
            // 
            this.label7.AutoSize = true;
            this.label7.Location = new System.Drawing.Point(5, 5);
            this.label7.Name = "label7";
            this.label7.Size = new System.Drawing.Size(114, 13);
            this.label7.TabIndex = 7;
            this.label7.Text = "Output File Destination";
            // 
            // panel1
            // 
            this.panel1.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.panel1.Controls.Add(this.label2);
            this.panel1.Controls.Add(this.label1);
            this.panel1.Controls.Add(this.cmbSegGroup);
            this.panel1.Controls.Add(this.cmbSegJob);
            this.panel1.Controls.Add(this.rbAllAccounts);
            this.panel1.Controls.Add(this.rbSegmentationInput);
            this.panel1.Controls.Add(this.label4);
            this.panel1.Location = new System.Drawing.Point(8, 32);
            this.panel1.Name = "panel1";
            this.panel1.Size = new System.Drawing.Size(376, 161);
            this.panel1.TabIndex = 8;
            // 
            // label2
            // 
            this.label2.AutoSize = true;
            this.label2.Location = new System.Drawing.Point(26, 110);
            this.label2.Name = "label2";
            this.label2.Size = new System.Drawing.Size(104, 13);
            this.label2.TabIndex = 13;
            this.label2.Text = "Segmentation Group";
            // 
            // label1
            // 
            this.label1.AutoSize = true;
            this.label1.Location = new System.Drawing.Point(26, 68);
            this.label1.Name = "label1";
            this.label1.Size = new System.Drawing.Size(92, 13);
            this.label1.TabIndex = 12;
            this.label1.Text = "Segmentation Job";
            // 
            // cmbSegGroup
            // 
            this.cmbSegGroup.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.cmbSegGroup.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbSegGroup.Enabled = false;
            this.cmbSegGroup.Location = new System.Drawing.Point(29, 126);
            this.cmbSegGroup.Name = "cmbSegGroup";
            this.cmbSegGroup.Size = new System.Drawing.Size(335, 21);
            this.cmbSegGroup.TabIndex = 11;
            // 
            // cmbSegJob
            // 
            this.cmbSegJob.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.cmbSegJob.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbSegJob.Enabled = false;
            this.cmbSegJob.Location = new System.Drawing.Point(29, 84);
            this.cmbSegJob.Name = "cmbSegJob";
            this.cmbSegJob.Size = new System.Drawing.Size(335, 21);
            this.cmbSegJob.TabIndex = 10;
            this.cmbSegJob.SelectedIndexChanged += new System.EventHandler(this.cmbSegJob_SelectedIndexChanged);
            // 
            // rbAllAccounts
            // 
            this.rbAllAccounts.Checked = true;
            this.rbAllAccounts.Location = new System.Drawing.Point(8, 21);
            this.rbAllAccounts.Name = "rbAllAccounts";
            this.rbAllAccounts.Size = new System.Drawing.Size(104, 24);
            this.rbAllAccounts.TabIndex = 8;
            this.rbAllAccounts.TabStop = true;
            this.rbAllAccounts.Text = "All Accounts";
            this.rbAllAccounts.CheckedChanged += new System.EventHandler(this.rbAllAccounts_CheckedChanged);
            // 
            // rbSegmentationInput
            // 
            this.rbSegmentationInput.Location = new System.Drawing.Point(8, 42);
            this.rbSegmentationInput.Name = "rbSegmentationInput";
            this.rbSegmentationInput.Size = new System.Drawing.Size(176, 24);
            this.rbSegmentationInput.TabIndex = 9;
            this.rbSegmentationInput.Text = "Segmentation Job Input";
            this.rbSegmentationInput.CheckedChanged += new System.EventHandler(this.rbSegmentationInput_CheckedChanged);
            // 
            // label4
            // 
            this.label4.AutoSize = true;
            this.label4.Location = new System.Drawing.Point(5, 5);
            this.label4.Name = "label4";
            this.label4.Size = new System.Drawing.Size(90, 13);
            this.label4.TabIndex = 7;
            this.label4.Text = "Output file source";
            // 
            // label3
            // 
            this.label3.AutoSize = true;
            this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label3.Location = new System.Drawing.Point(5, 8);
            this.label3.Name = "label3";
            this.label3.Size = new System.Drawing.Size(111, 15);
            this.label3.TabIndex = 6;
            this.label3.Text = "Output File Options";
            // 
            // tabImportAddresses
            // 
            this.tabImportAddresses.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.tabImportAddresses.Controls.Add(this.panel4);
            this.tabImportAddresses.Controls.Add(this.btnImportAddresses);
            this.tabImportAddresses.Controls.Add(this.panel3);
            this.tabImportAddresses.Controls.Add(this.label6);
            this.tabImportAddresses.Location = new System.Drawing.Point(4, 22);
            this.tabImportAddresses.Name = "tabImportAddresses";
            this.tabImportAddresses.Padding = new System.Windows.Forms.Padding(3);
            this.tabImportAddresses.Size = new System.Drawing.Size(400, 294);
            this.tabImportAddresses.TabIndex = 1;
            this.tabImportAddresses.Text = "Import Addresses";
            this.tabImportAddresses.UseVisualStyleBackColor = true;
            // 
            // panel4
            // 
            this.panel4.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.panel4.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.panel4.Controls.Add(this.cmbCodeValue);
            this.panel4.Controls.Add(this.chkProperCase);
            this.panel4.Controls.Add(this.chkAddCode);
            this.panel4.Controls.Add(this.label10);
            this.panel4.Controls.Add(this.label11);
            this.panel4.Controls.Add(this.cmbCodeType);
            this.panel4.Controls.Add(this.txtNoteValue);
            this.panel4.Controls.Add(this.chkAddNote);
            this.panel4.Controls.Add(this.label8);
            this.panel4.Controls.Add(this.label9);
            this.panel4.Controls.Add(this.cmbNoteType);
            this.panel4.Location = new System.Drawing.Point(8, 32);
            this.panel4.Name = "panel4";
            this.panel4.Size = new System.Drawing.Size(376, 161);
            this.panel4.TabIndex = 0;
            // 
            // cmbCodeValue
            // 
            this.cmbCodeValue.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.cmbCodeValue.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbCodeValue.Enabled = false;
            this.cmbCodeValue.Location = new System.Drawing.Point(138, 108);
            this.cmbCodeValue.Name = "cmbCodeValue";
            this.cmbCodeValue.Size = new System.Drawing.Size(226, 21);
            this.cmbCodeValue.TabIndex = 5;
            // 
            // chkProperCase
            // 
            this.chkProperCase.AutoSize = true;
            this.chkProperCase.Location = new System.Drawing.Point(8, 135);
            this.chkProperCase.Name = "chkProperCase";
            this.chkProperCase.Size = new System.Drawing.Size(189, 17);
            this.chkProperCase.TabIndex = 6;
            this.chkProperCase.Text = "Proper case names and addresses";
            this.chkProperCase.UseVisualStyleBackColor = true;
            this.chkProperCase.CheckedChanged += new System.EventHandler(this.chkProperCase_CheckedChanged);
            // 
            // chkAddCode
            // 
            this.chkAddCode.AutoSize = true;
            this.chkAddCode.Location = new System.Drawing.Point(8, 70);
            this.chkAddCode.Name = "chkAddCode";
            this.chkAddCode.Size = new System.Drawing.Size(235, 17);
            this.chkAddCode.TabIndex = 3;
            this.chkAddCode.Text = "Add a code type and value to each account";
            this.chkAddCode.UseVisualStyleBackColor = true;
            this.chkAddCode.CheckedChanged += new System.EventHandler(this.chkAddCode_CheckedChanged);
            // 
            // label10
            // 
            this.label10.AutoSize = true;
            this.label10.Location = new System.Drawing.Point(135, 92);
            this.label10.Name = "label10";
            this.label10.Size = new System.Drawing.Size(62, 13);
            this.label10.TabIndex = 18;
            this.label10.Text = "Code Value";
            // 
            // label11
            // 
            this.label11.AutoSize = true;
            this.label11.Location = new System.Drawing.Point(10, 92);
            this.label11.Name = "label11";
            this.label11.Size = new System.Drawing.Size(59, 13);
            this.label11.TabIndex = 17;
            this.label11.Text = "Code Type";
            // 
            // cmbCodeType
            // 
            this.cmbCodeType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbCodeType.Enabled = false;
            this.cmbCodeType.Location = new System.Drawing.Point(13, 108);
            this.cmbCodeType.Name = "cmbCodeType";
            this.cmbCodeType.Size = new System.Drawing.Size(111, 21);
            this.cmbCodeType.TabIndex = 4;
            this.cmbCodeType.SelectedIndexChanged += new System.EventHandler(this.cmbCodeType_SelectedIndexChanged);
            // 
            // txtNoteValue
            // 
            this.txtNoteValue.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.txtNoteValue.Enabled = false;
            this.txtNoteValue.Location = new System.Drawing.Point(138, 43);
            this.txtNoteValue.Name = "txtNoteValue";
            this.txtNoteValue.Size = new System.Drawing.Size(226, 20);
            this.txtNoteValue.TabIndex = 2;
            // 
            // chkAddNote
            // 
            this.chkAddNote.AutoSize = true;
            this.chkAddNote.Location = new System.Drawing.Point(8, 5);
            this.chkAddNote.Name = "chkAddNote";
            this.chkAddNote.Size = new System.Drawing.Size(232, 17);
            this.chkAddNote.TabIndex = 0;
            this.chkAddNote.Text = "Add a note type and value to each account";
            this.chkAddNote.UseVisualStyleBackColor = true;
            this.chkAddNote.CheckedChanged += new System.EventHandler(this.chkAddNote_CheckedChanged);
            // 
            // label8
            // 
            this.label8.AutoSize = true;
            this.label8.Location = new System.Drawing.Point(135, 25);
            this.label8.Name = "label8";
            this.label8.Size = new System.Drawing.Size(30, 13);
            this.label8.TabIndex = 13;
            this.label8.Text = "Note";
            // 
            // label9
            // 
            this.label9.AutoSize = true;
            this.label9.Location = new System.Drawing.Point(16, 27);
            this.label9.Name = "label9";
            this.label9.Size = new System.Drawing.Size(57, 13);
            this.label9.TabIndex = 12;
            this.label9.Text = "Note Type";
            // 
            // cmbNoteType
            // 
            this.cmbNoteType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.cmbNoteType.Enabled = false;
            this.cmbNoteType.Location = new System.Drawing.Point(19, 43);
            this.cmbNoteType.Name = "cmbNoteType";
            this.cmbNoteType.Size = new System.Drawing.Size(111, 21);
            this.cmbNoteType.TabIndex = 1;
            // 
            // btnImportAddresses
            // 
            this.btnImportAddresses.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
            this.btnImportAddresses.Location = new System.Drawing.Point(129, 262);
            this.btnImportAddresses.Name = "btnImportAddresses";
            this.btnImportAddresses.Size = new System.Drawing.Size(128, 23);
            this.btnImportAddresses.TabIndex = 15;
            this.btnImportAddresses.Text = "Import Addresses";
            this.btnImportAddresses.UseVisualStyleBackColor = true;
            this.btnImportAddresses.Click += new System.EventHandler(this.btnImportAddresses_Click);
            // 
            // panel3
            // 
            this.panel3.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.panel3.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
            this.panel3.Controls.Add(this.btnOpenDialog);
            this.panel3.Controls.Add(this.txtInputFile);
            this.panel3.Controls.Add(this.label5);
            this.panel3.Location = new System.Drawing.Point(8, 201);
            this.panel3.Name = "panel3";
            this.panel3.Size = new System.Drawing.Size(376, 54);
            this.panel3.TabIndex = 1;
            // 
            // btnOpenDialog
            // 
            this.btnOpenDialog.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
            this.btnOpenDialog.Location = new System.Drawing.Point(339, 24);
            this.btnOpenDialog.Name = "btnOpenDialog";
            this.btnOpenDialog.Size = new System.Drawing.Size(25, 20);
            this.btnOpenDialog.TabIndex = 14;
            this.btnOpenDialog.Text = "...";
            this.btnOpenDialog.UseVisualStyleBackColor = true;
            this.btnOpenDialog.Click += new System.EventHandler(this.btnOpenDialog_Click);
            // 
            // txtInputFile
            // 
            this.txtInputFile.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.txtInputFile.Location = new System.Drawing.Point(8, 24);
            this.txtInputFile.Name = "txtInputFile";
            this.txtInputFile.Size = new System.Drawing.Size(328, 20);
            this.txtInputFile.TabIndex = 7;
            // 
            // label5
            // 
            this.label5.AutoSize = true;
            this.label5.Location = new System.Drawing.Point(5, 5);
            this.label5.Name = "label5";
            this.label5.Size = new System.Drawing.Size(87, 13);
            this.label5.TabIndex = 7;
            this.label5.Text = "Input File Source";
            // 
            // label6
            // 
            this.label6.AutoSize = true;
            this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
            this.label6.Location = new System.Drawing.Point(5, 9);
            this.label6.Name = "label6";
            this.label6.Size = new System.Drawing.Size(102, 15);
            this.label6.TabIndex = 11;
            this.label6.Text = "Input File Options";
            // 
            // saveFileDialog
            // 
            this.saveFileDialog.DefaultExt = "csv";
            this.saveFileDialog.Title = "Select Output File";
            // 
            // statusStrip1
            // 
            this.statusStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.toolStripStatusLabel});
            this.statusStrip1.Location = new System.Drawing.Point(0, 356);
            this.statusStrip1.Name = "statusStrip1";
            this.statusStrip1.Size = new System.Drawing.Size(424, 22);
            this.statusStrip1.SizingGrip = false;
            this.statusStrip1.TabIndex = 1;
            this.statusStrip1.Text = "statusStrip1";
            // 
            // toolStripStatusLabel
            // 
            this.toolStripStatusLabel.Name = "toolStripStatusLabel";
            this.toolStripStatusLabel.Size = new System.Drawing.Size(0, 17);
            // 
            // menuStrip
            // 
            this.menuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.fileToolStripMenuItem,
            this.helpToolStripMenuItem});
            this.menuStrip.Location = new System.Drawing.Point(0, 0);
            this.menuStrip.Name = "menuStrip";
            this.menuStrip.Size = new System.Drawing.Size(424, 24);
            this.menuStrip.TabIndex = 2;
            this.menuStrip.Text = "menuStrip1";
            // 
            // fileToolStripMenuItem
            // 
            this.fileToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.connectToMPXToolStripMenuItem,
            this.disconnectFromMPXToolStripMenuItem,
            this.toolStripMenuItem1,
            this.outputToolStripMenuItem,
            this.inputToolStripMenuItem});
            this.fileToolStripMenuItem.Name = "fileToolStripMenuItem";
            this.fileToolStripMenuItem.Size = new System.Drawing.Size(35, 20);
            this.fileToolStripMenuItem.Text = "&File";
            // 
            // connectToMPXToolStripMenuItem
            // 
            this.connectToMPXToolStripMenuItem.Name = "connectToMPXToolStripMenuItem";
            this.connectToMPXToolStripMenuItem.Size = new System.Drawing.Size(185, 22);
            this.connectToMPXToolStripMenuItem.Text = "&Connect to MPX";
            this.connectToMPXToolStripMenuItem.Click += new System.EventHandler(this.connectToMPXToolStripMenuItem_Click);
            // 
            // toolStripMenuItem1
            // 
            this.toolStripMenuItem1.Name = "toolStripMenuItem1";
            this.toolStripMenuItem1.Size = new System.Drawing.Size(182, 6);
            // 
            // outputToolStripMenuItem
            // 
            this.outputToolStripMenuItem.Name = "outputToolStripMenuItem";
            this.outputToolStripMenuItem.Size = new System.Drawing.Size(185, 22);
            this.outputToolStripMenuItem.Text = "&Output Addresses";
            this.outputToolStripMenuItem.Click += new System.EventHandler(this.outputToolStripMenuItem_Click);
            // 
            // inputToolStripMenuItem
            // 
            this.inputToolStripMenuItem.Name = "inputToolStripMenuItem";
            this.inputToolStripMenuItem.Size = new System.Drawing.Size(185, 22);
            this.inputToolStripMenuItem.Text = "&Input Addresses";
            this.inputToolStripMenuItem.Click += new System.EventHandler(this.inputToolStripMenuItem_Click);
            // 
            // helpToolStripMenuItem
            // 
            this.helpToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
            this.aboutToolStripMenuItem});
            this.helpToolStripMenuItem.Name = "helpToolStripMenuItem";
            this.helpToolStripMenuItem.Size = new System.Drawing.Size(40, 20);
            this.helpToolStripMenuItem.Text = "&Help";
            // 
            // aboutToolStripMenuItem
            // 
            this.aboutToolStripMenuItem.Name = "aboutToolStripMenuItem";
            this.aboutToolStripMenuItem.Size = new System.Drawing.Size(114, 22);
            this.aboutToolStripMenuItem.Text = "&About";
            this.aboutToolStripMenuItem.Click += new System.EventHandler(this.aboutToolStripMenuItem_Click);
            // 
            // disconnectFromMPXToolStripMenuItem
            // 
            this.disconnectFromMPXToolStripMenuItem.Name = "disconnectFromMPXToolStripMenuItem";
            this.disconnectFromMPXToolStripMenuItem.Size = new System.Drawing.Size(185, 22);
            this.disconnectFromMPXToolStripMenuItem.Text = "Disconnect from MPX";
            this.disconnectFromMPXToolStripMenuItem.Click += new System.EventHandler(this.disconnectFromMPXToolStripMenuItem_Click);
            // 
            // frmMain
            // 
            this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
            this.ClientSize = new System.Drawing.Size(424, 378);
            this.Controls.Add(this.statusStrip1);
            this.Controls.Add(this.menuStrip);
            this.Controls.Add(this.tabControlMain);
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.MainMenuStrip = this.menuStrip;
            this.Name = "frmMain";
            this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
            this.Text = "MPX Address Update Utility";
            this.Load += new System.EventHandler(this.frmMain_Load);
            this.tabControlMain.ResumeLayout(false);
            this.tabOutputAddresses.ResumeLayout(false);
            this.tabOutputAddresses.PerformLayout();
            this.panel2.ResumeLayout(false);
            this.panel2.PerformLayout();
            this.panel1.ResumeLayout(false);
            this.panel1.PerformLayout();
            this.tabImportAddresses.ResumeLayout(false);
            this.tabImportAddresses.PerformLayout();
            this.panel4.ResumeLayout(false);
            this.panel4.PerformLayout();
            this.panel3.ResumeLayout(false);
            this.panel3.PerformLayout();
            this.statusStrip1.ResumeLayout(false);
            this.statusStrip1.PerformLayout();
            this.menuStrip.ResumeLayout(false);
            this.menuStrip.PerformLayout();
            this.ResumeLayout(false);
            this.PerformLayout();

		}
		#endregion

		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main() 
		{
			System.Windows.Forms.Application.Run(new frmMain());
		}

		private void frmMain_Load(object sender, System.EventArgs e)
		{
            ConnectToMpx();
		}

        private void connectToMPXToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ConnectToMpx();
        }

        private void disconnectFromMPXToolStripMenuItem_Click(object sender, EventArgs e)
        {
            DisconnectFromMpx();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmAbout frmAbout = new frmAbout();
            frmAbout.ShowDialog();
            frmAbout.Dispose();
        }

        private void ConnectToMpx()
        {
            try
            {
                MpxConnection = new MpxConnection();
                // This will cause the connector to log into the server
                MpxSession session = MpxConnection.MpxSessionList.GetMpxSession();
                string userName = session.UserName;
                toolStripStatusLabel.Text = "Connected to MPX application server as user " + userName + ".";
                EnableControls();
            }
            catch (Exception exception)
            {
                LogError(exception);
            }
        }

        private void DisconnectFromMpx()
        {
            try
            {
                MpxConnection.MpxSessionList.GetMpxSession().LogOff();
                DisableControls();
                toolStripStatusLabel.Text = "Not connected to MPX.";
            }
            catch (Exception exception)
            {
                LogError(exception);
            }
        }

        private void EnableControls()
        {
            tabControlMain.Enabled = true;
            outputToolStripMenuItem.Enabled = true;
            inputToolStripMenuItem.Enabled = true;
        }

        private void DisableControls()
        {
            tabControlMain.Enabled = false;
            outputToolStripMenuItem.Enabled = false;
            inputToolStripMenuItem.Enabled = false;
        }

        private void LogError(Exception exception)
        {
            try
            {
                string message = "Error occured connecting to MPX application server.  Please check the log file specified in the MpowerSystems.MpxConnector.config file for more information." + "\r\n" + exception.Message;
                if (exception.InnerException != null && exception.InnerException.Message.Length > 0)
                    message += "\r\n" + exception.InnerException.Message;
                MpxConnection.Log.Logger.Error(message + exception.StackTrace);
                MessageBox.Show(message);
                DisableControls();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }

        public MpxConnection MpxConnection
        {
            get { return _mpxConnection; }
            set { _mpxConnection = value; }
        }

        #region Output
        private void rbSegmentationInput_CheckedChanged(object sender, EventArgs e)
        {
            InputChanged();
        }

        private void rbAllAccounts_CheckedChanged(object sender, EventArgs e)
        {
            InputChanged();
        }

		private void InputChanged()
		{
            cmbSegGroup.Enabled = rbSegmentationInput.Checked;
            cmbSegJob.Enabled = rbSegmentationInput.Checked;

			if (rbSegmentationInput.Checked)
			{
				LoadSegmentationJobs();
			}

			if (rbAllAccounts.Checked)
			{
				cmbSegJob.Text = "";
			}
		}

        private void cmbSegJob_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbSegJob.SelectedIndex != -1)
            {
                LoadSegmentationGroups();
            }
        }

        private void btnSaveDialog_Click(object sender, EventArgs e)
        {
            if (txtOutputFile.Text.Length > 0)
            {
                if (File.Exists(txtOutputFile.Text))
                    saveFileDialog.FileName = txtOutputFile.Text;
                if (Directory.Exists(Path.GetDirectoryName(txtOutputFile.Text)))
                    saveFileDialog.InitialDirectory = Path.GetDirectoryName(txtOutputFile.Text);
            }
            DialogResult dialogResult = saveFileDialog.ShowDialog();
            if (dialogResult == DialogResult.OK)
                txtOutputFile.Text = saveFileDialog.FileName;            
        }

        private void outputToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControlMain.SelectedTab = tabOutputAddresses;
            OutputAddresses();
        }

        private void btnOutputAddresses_Click(object sender, EventArgs e)
        {
            OutputAddresses();
        }

        private void OutputAddresses()
        {
            DisableControls();
            try
            {
                if (ValidateOutputOptions())
                {
                    if (MessageBox.Show("Export addresses?", "Address Export Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        MpxConnection.Log.Logger.Info("Export Process - Preparing to export accounts.");
                        if (File.Exists(txtOutputFile.Text))
                            File.Delete(txtOutputFile.Text);
                        // Find Report, create it if it does not exist
                        toolStripStatusLabel.Text = "Export process starting...";
                        long reportId = GetReportId();
                        ExportReportResponse exportReportResponse = MpxConnection.ExportReport(new ExportReportRequest(reportId));
                        GetReportExportStatusResponse getReportExportStatusResponse = MpxConnection.GetReportExportStatus(new GetReportExportStatusRequest(exportReportResponse.ReportRunId));
                        toolStripStatusLabel.Text = getReportExportStatusResponse.StatusDescription;
                        while (getReportExportStatusResponse.Status != EnumReportExportStatus.Complete
                            && getReportExportStatusResponse.Status != EnumReportExportStatus.Failed)
                        {
                            System.Windows.Forms.Application.DoEvents();
                            System.Threading.Thread.Sleep(250);
                            getReportExportStatusResponse = MpxConnection.GetReportExportStatus(new GetReportExportStatusRequest(exportReportResponse.ReportRunId));
                            toolStripStatusLabel.Text = getReportExportStatusResponse.StatusDescription;
                        }
                        if (!Directory.Exists(Path.GetDirectoryName(txtOutputFile.Text)))
                            Directory.CreateDirectory(Path.GetDirectoryName(txtOutputFile.Text));
                        if (!File.Exists(getReportExportStatusResponse.OutputFile))
                        {
                            throw new ApplicationException("Report export file not found.  This could indicate an invalid exportdirectory or exporturl setting in the MpowerSystems.MpxConnector.config file.");
                        }
                        File.Copy(getReportExportStatusResponse.OutputFile, txtOutputFile.Text);
                        File.Delete(getReportExportStatusResponse.OutputFile);
                        if (File.Exists(txtOutputFile.Text))
                            MessageBox.Show("Export complete.");
                        toolStripStatusLabel.Text = "Export complete.";
                        MpxConnection.Log.Logger.Info("Export Process - Export complete.");
                    }
                    else
                    {
                        toolStripStatusLabel.Text = "Export canceled.";
                    }
                }
            }
            catch (Exception exception)
            {
                LogError(exception);
            }
            finally
            {
                EnableControls();
            }
        }

        private bool ValidateOutputOptions()
        {
            if (rbSegmentationInput.Checked)
            {
                if (cmbSegJob.Text.Length == 0)
                {
                    EnableControls();
                    cmbSegJob.Focus();
                    throw new ApplicationException("No segmentation job selected.");
                }
                if (cmbSegGroup.Text.Length == 0)
                {
                    EnableControls();
                    cmbSegGroup.Focus();
                    throw new ApplicationException("No segmentation group selected.");
                }
            }
            if (txtOutputFile.Text.Length == 0)
            {
                EnableControls();
                txtOutputFile.Focus();
                throw new ApplicationException("No directory and file name selected for output file.");
            }
            if (!Directory.Exists(Path.GetDirectoryName(txtOutputFile.Text)))
            {
                EnableControls();
                txtOutputFile.Focus();
                throw new ApplicationException("Invalid directory selected for output file.");
            }
            return true;
        }

        private void LoadSegmentationJobs()
        {
            try
            {
                cmbSegJob.Items.Clear();

                GetSegmentationsRequest getSegmentationsRequest = new GetSegmentationsRequest();
                GetSegmentationsResponse getSegmentationsResponse = MpxConnection.GetSegmentations(getSegmentationsRequest);

                if (getSegmentationsResponse != null && getSegmentationsResponse.Segmentations != null)
                {
                    foreach (Segmentation segmentation in getSegmentationsResponse.Segmentations)
                    {
                        string jobId = segmentation.SegmentationId.ToString();
                        string jobName = segmentation.Name;

                        cmbSegJob.Items.Add(jobId.PadRight(6, ' ') + "  :  " + jobName);
                    }
                }
            }
            catch (Exception exception)
            {
                LogError(exception);
            }
        }

        private void LoadSegmentationGroups()
        {
            try
            {
                cmbSegGroup.Items.Clear();

                if (cmbSegJob.Text.Length > 0)
                {
                    string segJobID = cmbSegJob.Text.Substring(0, 6).Trim();
                    GetSegmentationGroupsRequest getSegGroupRequest = new GetSegmentationGroupsRequest(null, Convert.ToInt64(segJobID), null, null, false);
                    GetSegmentationGroupsResponse getSegGroupResponse = MpxConnection.GetSegmentationGroups(getSegGroupRequest);

                    if (getSegGroupResponse != null && getSegGroupResponse.SegmentationGroups != null)
                    {
                        foreach (SegmentationGroup segmentationGroup in getSegGroupResponse.SegmentationGroups)
                        {
                            EntitySet group = MpxConnection.MpxSessionList.GetMpxSession().Projects.GetSegmentationGroup(new TID(segmentationGroup.SegmentationGroupId));
                            string groupId = group.DataSet.Tables[SegmentationGrpsEntity.NAME_SEGMENTATIONGRPSENTITY].Rows[0][SegmentationGrpsEntity.FldNumber].ToString();
                            string groupName = segmentationGroup.Name;
                            string accounts = segmentationGroup.AccountCount.ToString();

                            cmbSegGroup.Items.Add(groupId.PadRight(6, ' ') + "  :  " + groupName
                                + "  --  Record count : " + accounts);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                LogError(exception);
            }
        }

        private long GetReportId()
        {
            long reportId = -1;
            try
            {
                GetReportsResponse getReportsResponse = FindReport();
                if (getReportsResponse != null && getReportsResponse.Reports != null && getReportsResponse.Reports.Count > 0)
                {
                    reportId = getReportsResponse.Reports[0].ReportId.Value;
                }
                reportId = BuildReport(reportId);
            }
            catch (Exception exception)
            {
                LogError(exception);
            }
            return reportId;
        }

        private GetReportsResponse FindReport()
        {
            GetReportsResponse getReportsResponse = null;
            try
            {
                GetReportsRequest getReportsRequest = new GetReportsRequest();
                getReportsRequest.Title = _reportName;
                getReportsResponse = MpxConnection.GetReports(getReportsRequest);
            }
            catch (Exception exception)
            {
                LogError(exception);
            }
            return getReportsResponse;
        }

        private long BuildReport(long reportId)
        {
            try
            {
                Report report = null;
                if (reportId > 0)
                {
                    GetReportsResponse getReportsResponse = MpxConnection.GetReports(new GetReportsRequest(reportId, null, null, null));
                    if (getReportsResponse.Reports.Count > 0)
                        report = getReportsResponse.Reports[0];
                }
                if (report == null)
                {
                    report = new Report();
                }
                report.Title = _reportName;
                report.Description = _reportName;
                report.Type = EnumReportTypes.People;
                if (rbSegmentationInput.Checked)
                {
                    string sourceFile =
                        Path.Combine(MpxConnection.MpxSessionList.GetMpxSession().Session.Settings.SegmentationOutputLocation,
                        "S" + cmbSegJob.Text.Substring(0, 6).Trim()
                        + "G" + cmbSegGroup.Text.Substring(0, 6).Trim() + ".txt");
                    if (!File.Exists(sourceFile))
                        throw new ApplicationException("Source segmentation file (" + sourceFile + ") could not be found.  Re-running the segmenation have solve this.");
                    report.InputSource = sourceFile;
                }
                else
                {
                    report.InputSource = null;
                }
                report.QueryType = EnumQueryTypes.Basic;
                report.Criteria = new List<ReportCriteria>();
                report.Criteria.Add(new ReportCriteria());
                report.SortOrder = new List<ReportSort>();
                report.GroupBy = new List<ReportGroupBy>();
                report.Fields = new List<ReportField>();

                report.Fields.Add(new ReportField(0, "People.AcctNbr", EnumReportFieldAggregateFunction.None));
                report.Fields.Add(new ReportField(1, "People.Title", EnumReportFieldAggregateFunction.None));
                report.Fields.Add(new ReportField(2, "People.FirstName", EnumReportFieldAggregateFunction.None));
                report.Fields.Add(new ReportField(3, "People.MiddleName", EnumReportFieldAggregateFunction.None));
                report.Fields.Add(new ReportField(4, "People.LastName", EnumReportFieldAggregateFunction.None));
                report.Fields.Add(new ReportField(5, "People.Suffix", EnumReportFieldAggregateFunction.None));
                report.Fields.Add(new ReportField(6, "People.Organization", EnumReportFieldAggregateFunction.None));
                report.Fields.Add(new ReportField(7, "People.IsOrganization", EnumReportFieldAggregateFunction.None));
                report.Fields.Add(new ReportField(8, "People.Address", EnumReportFieldAggregateFunction.None));
                report.Fields.Add(new ReportField(9, "People.City", EnumReportFieldAggregateFunction.None));
                report.Fields.Add(new ReportField(10, "People.State", EnumReportFieldAggregateFunction.None));
                report.Fields.Add(new ReportField(11, "People.ZipCode", EnumReportFieldAggregateFunction.None));
                report.Fields.Add(new ReportField(12, "People.Country", EnumReportFieldAggregateFunction.None));

                if (reportId > 0)
                {
                    UpdateReportRequest updateReportRequest = new UpdateReportRequest();
                    updateReportRequest.Report = report;
                    UpdateReportResponse updateReportsResponse = MpxConnection.UpdateReport(updateReportRequest);
                }
                else
                {
                    InsertReportRequest insertReportRequest = new InsertReportRequest();
                    insertReportRequest.Report = report;
                    InsertReportResponse insertReportsResponse = MpxConnection.InsertReport(insertReportRequest);
                    reportId = insertReportRequest.Report.ReportId.GetValueOrDefault(-1);
                }

                return reportId;
            }
            catch (Exception exception)
            {
                LogError(exception);
            }
            return -1;
        }
        #endregion

        #region Input
        private void chkAddNote_CheckedChanged(object sender, EventArgs e)
        {
            cmbNoteType.Enabled = chkAddNote.Checked;
            txtNoteValue.Enabled = chkAddNote.Checked;
            LoadNoteTypes();
        }

        private void chkAddCode_CheckedChanged(object sender, EventArgs e)
        {
            cmbCodeType.Enabled = chkAddCode.Checked;
            cmbCodeValue.Enabled = chkAddCode.Checked;
            LoadCodeTypes();
        }

        private void cmbCodeType_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbCodeType.SelectedIndex != -1)
            {
                LoadCodeValues();
            }
        }

        private void chkProperCase_CheckedChanged(object sender, EventArgs e)
        {
            if (chkProperCase.Checked)
            {
                MessageBox.Show("This feature has not yet been implemented.");
                chkProperCase.Checked = false;
            }
        }

        private void LoadNoteTypes()
        {
            try
            {
                cmbSegJob.Items.Clear();

                GetNoteTypesRequest getNoteTypesRequest = new GetNoteTypesRequest();
                GetNoteTypesResponse getNoteTypesResponse = MpxConnection.GetNoteTypes(getNoteTypesRequest);

                if (getNoteTypesResponse != null && getNoteTypesResponse.NoteTypes != null)
                {
                    foreach (NoteType noteType in getNoteTypesResponse.NoteTypes)
                    {
                        cmbNoteType.Items.Add(noteType.NoteTypeValue);
                    }
                }
            }
            catch (Exception exception)
            {
                LogError(exception);
            }
        }

        private void LoadCodeTypes()
        {
            try
            {
                cmbSegJob.Items.Clear();

                GetCodeTypesRequest getCodeTypesRequest = new GetCodeTypesRequest();
                GetCodeTypesResponse getCodeTypesResponse = MpxConnection.GetCodeTypes(getCodeTypesRequest);

                if (getCodeTypesResponse != null && getCodeTypesResponse.CodeTypes != null)
                {
                    foreach (CodeType codeType in getCodeTypesResponse.CodeTypes)
                    {
                        cmbCodeType.Items.Add(codeType.CodeTypeValue);
                    }
                }
            }
            catch (Exception exception)
            {
                LogError(exception);
            }
        }

        private void LoadCodeValues()
        {
            try
            {
                cmbCodeValue.Items.Clear();

                GetCodesRequest getCodesRequest = new GetCodesRequest();
                getCodesRequest.CodeType = cmbCodeType.Text;
                GetCodesResponse getCodesResponse = MpxConnection.GetCodes(getCodesRequest);

                if (getCodesResponse != null && getCodesResponse.Codes != null)
                {
                    foreach (Code code in getCodesResponse.Codes)
                    {
                        cmbCodeValue.Items.Add(code.CodeValue);
                    }
                }
            }
            catch (Exception exception)
            {
                LogError(exception);
            }
        }

        private void btnOpenDialog_Click(object sender, EventArgs e)
        {
            if (txtInputFile.Text.Length > 0)
            {
                if (File.Exists(txtInputFile.Text))
                    openFileDialog.FileName = txtInputFile.Text;
                if (Directory.Exists(Path.GetDirectoryName(txtInputFile.Text)))
                    openFileDialog.InitialDirectory = Path.GetDirectoryName(txtInputFile.Text);
            }   
            DialogResult dialogResult = openFileDialog.ShowDialog();
            if (dialogResult == DialogResult.OK)
                    txtInputFile.Text = openFileDialog.FileName;            
        }

        private void btnImportAddresses_Click(object sender, EventArgs e)
        {
            ImportAddresses();
        }

        private void inputToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tabControlMain.SelectedTab = tabImportAddresses;
            ImportAddresses();
        }

        private bool ValidateInputOptions()
        {
            if (chkAddNote.Checked)
            {
                if (cmbNoteType.Text.Length == 0)
                {
                    EnableControls();
                    cmbNoteType.Focus();
                    throw new ApplicationException("No note type selected.");
                }
                if (txtNoteValue.Text.Length == 0)
                {
                    EnableControls();
                    txtNoteValue.Focus();
                    throw new ApplicationException("No note entered.");
                }
            }
            if (chkAddCode.Checked)
            {
                if (cmbCodeType.Text.Length == 0)
                {
                    EnableControls();
                    cmbCodeType.Focus();
                    throw new ApplicationException("No code type selected.");
                }
                if (cmbCodeValue.Text.Length == 0)
                {
                    EnableControls();
                    cmbCodeValue.Focus();
                    throw new ApplicationException("No code value selected.");
                }
            }
            if (txtInputFile.Text.Length == 0)
            {
                EnableControls();
                txtInputFile.Focus();
                throw new ApplicationException("No input file selected.");
            }
            if (!File.Exists(txtInputFile.Text))
            {
                EnableControls();
                txtInputFile.Focus();
                throw new ApplicationException("Input file does not exist.");
            }
            return true;
        }

        private void ImportAddresses()
        {
            DisableControls();
            CsvReader csvReader = null;
            AccountImportErrorLogWriter logWriter = null;
            bool headerAdded = false;
            try
            {
                if (ValidateInputOptions())
                {
                    if (MessageBox.Show("Import addresses?", "Address Import Confirmation", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        MpxConnection.Log.Logger.Info("Import Process - Preparing to import accounts.");
                        toolStripStatusLabel.Text = "Opening selected import file.";
                        logWriter = new AccountImportErrorLogWriter(Path.GetDirectoryName(txtInputFile.Text) + "ImportErrorLog.csv");
                        csvReader = new CsvReader(new StreamReader(txtInputFile.Text), true);
                        int fieldCount = csvReader.FieldCount;
                        string[] headers = csvReader.GetFieldHeaders();

                        // Prepare a hash table with the indexes of the field
                        Hashtable headersTable = new Hashtable();
                        for (int index = 0; index < headers.Length; index++)
                        {
                            headersTable.Add(headers[index], index);
                        }

                        int recordCount = 0;
                        int errorCount = 0;
                        while (csvReader.ReadNextRecord())
                        {
                            try
                            {
                                recordCount++;
                                toolStripStatusLabel.Text = "Processing record " + recordCount.ToString() + "...";
                                System.Windows.Forms.Application.DoEvents();
                                string message = "Account update failed.";
                                long entityId = Convert.ToInt64(csvReader[Convert.ToInt32(headersTable["EntityID"])]);
                                MpxConnection.Log.Logger.Info("Import Process - Importing Account " + entityId.ToString() + "."); 
                                GetAccountResponse getAccountResponse =
                                    MpxConnection.GetAccount(new GetAccountRequest(entityId));
                                if (getAccountResponse == null || getAccountResponse.Account == null)
                                {
                                    throw new ApplicationException(message);
                                }
                                Account account = getAccountResponse.Account;
                                if (headersTable["Title"] != null)
                                    account.Title = csvReader[Convert.ToInt32(headersTable["Title"])];
                                if (headersTable["FirstName"] != null)
                                    account.FirstName = csvReader[Convert.ToInt32(headersTable["FirstName"])];
                                if (headersTable["MiddleName"] != null)
                                    account.MiddleName = csvReader[Convert.ToInt32(headersTable["MiddleName"])];
                                if (headersTable["LastName"] != null)
                                    account.LastName = csvReader[Convert.ToInt32(headersTable["LastName"])];
                                if (headersTable["Suffix"] != null)
                                    account.Suffix = csvReader[Convert.ToInt32(headersTable["Suffix"])];
                                if (headersTable["OrgName"] != null)
                                    account.OrganizationName = csvReader[Convert.ToInt32(headersTable["OrgName"])];
                                if (headersTable["Addr1"] != null)
                                    account.Address1 = csvReader[Convert.ToInt32(headersTable["Addr1"])];
                                else if (headersTable["Address1"] != null)
                                    account.Address1 = csvReader[Convert.ToInt32(headersTable["Address1"])];
                                else
                                    account.Address1 = "";

                                if (headersTable["Addr2"] != null)
                                    account.Address2 = csvReader[Convert.ToInt32(headersTable["Addr2"])];
                                else if (headersTable["Address1"] != null)
                                    account.Address2 = csvReader[Convert.ToInt32(headersTable["Address2"])];
                                else
                                    account.Address2 = "";

                                if (headersTable["Addr3"] != null)
                                    account.Address3 = csvReader[Convert.ToInt32(headersTable["Addr3"])];
                                else if (headersTable["Address3"] != null)
                                    account.Address3 = csvReader[Convert.ToInt32(headersTable["Address3"])];
                                else
                                    account.Address3 = "";

                                if (headersTable["AddressCity"] != null)
                                    account.City = csvReader[Convert.ToInt32(headersTable["AddressCity"])];
                                if (headersTable["AddressState"] != null)
                                    account.State = csvReader[Convert.ToInt32(headersTable["AddressState"])];
                                if (headersTable["AddressZip"] != null)
                                    account.ZipCode = csvReader[Convert.ToInt32(headersTable["AddressZip"])];
                                if (headersTable["AddressCountry"] != null)
                                    account.Country = csvReader[Convert.ToInt32(headersTable["AddressCountry"])];

                                UpdateAccountRequest updateAccountRequest = new UpdateAccountRequest();
                                updateAccountRequest.Account = account;
                                updateAccountRequest.OverrideLock = true;
                                UpdateAccountResponse updateAccountResponse = MpxConnection.UpdateAccount(updateAccountRequest);
                                if (updateAccountResponse == null || !updateAccountResponse.Result)
                                {
                                    throw new ApplicationException(message);
                                }

                                if (chkAddCode.Checked)
                                {
                                    message = "Code insert failed.  Account information updated succesfully.";
                                    InsertAccountCodeRequest insertAccountCodeRequest = new InsertAccountCodeRequest();
                                    insertAccountCodeRequest.AccountCode = new AccountCode();
                                    insertAccountCodeRequest.AccountCode.AccountId = entityId;
                                    insertAccountCodeRequest.AccountCode.CodeType = cmbCodeType.Text;
                                    insertAccountCodeRequest.AccountCode.CodeValue = cmbCodeValue.Text;
                                    InsertAccountCodeResponse insertAccountCodeResponse = MpxConnection.InsertAccountCode(insertAccountCodeRequest);
                                    if (!insertAccountCodeResponse.Result)
                                    {
                                        throw new ApplicationException(message);
                                    }
                                }

                                if (chkAddNote.Checked)
                                {
                                    if (chkAddCode.Checked)
                                        message = "Note insert failed.  Account information updated and code inserted succesfully.";
                                    else
                                        message = "Note insert failed.  Account information updated succesfully.";
                                    InsertAccountNoteRequest insertAccountNoteRequest = new InsertAccountNoteRequest();
                                    insertAccountNoteRequest.AccountNote = new AccountNote();
                                    insertAccountNoteRequest.AccountNote.AccountId = entityId;
                                    insertAccountNoteRequest.AccountNote.NoteType = cmbNoteType.Text;
                                    insertAccountNoteRequest.AccountNote.Note = txtNoteValue.Text;
                                    InsertAccountNoteResponse insertAccountNoteResponse = MpxConnection.InsertAccountNote(insertAccountNoteRequest);
                                    if (!insertAccountNoteResponse.Result)
                                    {
                                        throw new ApplicationException(message);
                                    }
                                }
                                MpxConnection.Log.Logger.Info("Import Process - Account " + entityId.ToString() + " imported.");
                            }
                            catch (Exception exception)
                            {
                                errorCount++;
                                string message = exception.Message;
                                if (exception.InnerException != null && exception.InnerException.Message.Length > 0)
                                    message += "\r\n" + exception.InnerException.Message;
                                MpxConnection.Log.Logger.Error(message + exception.StackTrace);

                                StringBuilder sb = null;
                                // compile the record for the error log
                                if (!headerAdded)
                                {
                                    sb = new StringBuilder();
                                    for (int index = 0; index < fieldCount; index++)
                                    {
                                        sb.Append(csvReader.Quote +  headers[index] + csvReader.Quote + csvReader.Delimiter);
                                    }
                                    sb.Append(csvReader.Quote + "Error" + csvReader.Quote);
                                    logWriter.WriteAccountToErrorLog(sb.ToString());
                                    headerAdded = true;
                                }


                                sb = new StringBuilder();
                                for (int index = 0; index < fieldCount; index++)
                                {
                                    sb.Append(csvReader.Quote + csvReader[index] + csvReader.Quote + csvReader.Delimiter);
                                }
                                sb.Append(csvReader.Quote + exception.Message + csvReader.Quote);
                                logWriter.WriteAccountToErrorLog(sb.ToString());
                                continue;
                            }
                        }
                        MpxConnection.Log.Logger.Info("Import Process - Import complete.");
                        toolStripStatusLabel.Text = "Import complete.";
                        if (errorCount > 0)
                            MessageBox.Show("Import completed with " + errorCount.ToString() + " error(s) of out " + recordCount.ToString() + " record(s)."
                                + "\r\n\r\n" + "Accounts that encountered errors have been placed in"
                                + "\r\n" + Path.GetDirectoryName(txtInputFile.Text) + "ImportErrorLog.csv", "Import Complete");
                        else
                            MessageBox.Show("Import complete.", "Import Complete");
                    }
                    else
                    {
                        toolStripStatusLabel.Text = "Import canceled.";
                    }
                }
            }
            catch (Exception exception)
            {
                LogError(exception);
            }
            finally
            {
                if (csvReader != null)
                    csvReader.Dispose();
                if (logWriter != null)
                    logWriter.Close();
                EnableControls();
            }
        }
        #endregion      
    }
}
